/*
 * Copyright (C) 2010 Seapeak.Xu
 *
 * fostmq may be copied only under the terms of the GNU General
 * Public License V3, which may be found in the fostmq source kit.
 *
 * Created on: 2010-8-20
 * Author: Seapeak.Xu
 */

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>

#include "fost_buff.h"

/*
 * convert int32 value to stream buffer
 * parameters:
 * 	n:int value
 * 	buff:stream buffer
 * remarks:
 * 	the int value's sizeof is only 4
 * 	the stream buffer length is equal or more than 4,and end without '\0'
 */
void int2buff(const int n, char *buff)
{
	unsigned char *p;
	p = (unsigned char *) buff;
	*p++ = (n >> 24) & 0xFF;
	*p++ = (n >> 16) & 0xFF;
	*p++ = (n >> 8) & 0xFF;
	*p++ = n & 0xFF;
}

/*
 * convert stream buffer to int32 value
 * parameters:
 * 	buff:the stream buffer
 * return:
 * 	int32 value
 * remarks:
 * 	int value's sizeof is only 4
 * 	stream length is equal or more than 4 
 */
int buff2int(const char *buff)
{
	return (((unsigned char) (*buff)) << 24) | (((unsigned char) (*(buff + 1)))
			<< 16) | (((unsigned char) (*(buff + 2))) << 8)
			| ((unsigned char) (*(buff + 3)));
}

/*
 * convert int64(long long) value to stream buffer
 * parameters:
 * 	n:int64 value
 * 	buff:stream buffer
 * remarks:
 * 	int value's sizeof is only 8
 * 	stream buffer length is equal or more than 8,and end without '\0'
 */
void long2buff(int64_t n, char *buff)
{
	unsigned char *p;
	p = (unsigned char *) buff;
	*p++ = (n >> 56) & 0xFF;
	*p++ = (n >> 48) & 0xFF;
	*p++ = (n >> 40) & 0xFF;
	*p++ = (n >> 32) & 0xFF;
	*p++ = (n >> 24) & 0xFF;
	*p++ = (n >> 16) & 0xFF;
	*p++ = (n >> 8) & 0xFF;
	*p++ = n & 0xFF;
}

/*
 * convert stream buffer to int64(long long) value
 * parameters:
 * 	buff:the stream buffer
 * return:
 * 	the int64(long long) value
 * remarks:
 * 	the int value's sizeof is only 8
 * 	the stream length is more than 8 
 */
int64_t buff2long(const char *buff)
{
	unsigned char *p;
	p = (unsigned char *) buff;
	return (((int64_t) (*p)) << 56) | (((int64_t) (*(p + 1))) << 48)
			| (((int64_t) (*(p + 2))) << 40) | (((int64_t) (*(p + 3))) << 32)
			| (((int64_t) (*(p + 4))) << 24) | (((int64_t) (*(p + 5))) << 16)
			| (((int64_t) (*(p + 6))) << 8) | ((int64_t) (*(p + 7)));
}
